from flask import render_template, flash, redirect, g, url_for, session, request
from flask_login import login_user, current_user, login_required, logout_user
from flask_wtf import form

from app import app, lm, oid, db
#导入视图，视图是响应来自网页浏览器的请求的处理器。在 Flask 中，视图是编写成 Python 函数。
# 每一个视图函数是映射到一个或多个请求的 URL
#其实这个视图是非常简单，它只是返回一个字符串，在客户端的网页浏览器上显示。
# 两个 route 装饰器创建了从网址 / 以及 /index 到这个函数的映射。
from .forms import LoginForm
from app.models import User


@app.route('/')
@app.route('/index')
@login_required
def index():
    user = g.user
    posts = [
        {
            'author': {'username': 'John'},
            'body': 'Beautiful day in Portland!'
        },
        {
            'author': {'username': 'Susan'},
            'body': 'The Avengers movie was so cool!'
        }
    ]
    return render_template('index.html',
                           title='Home',
                           user=user,
                           posts=posts)
# index view function suppressed for brevity
#所以基本上，我们已经导入 LoginForm 类，从这个类实例化一个对象，
# 接着把它传入到模板中。这就是我们渲染表单所有要做的。
@app.route('/login', methods = ['GET', 'POST'])
@oid.loginhandler
def login():
    if g.user is not None and g.user.is_authenticated():
        return  redirect(url_for('index'))

    form = LoginForm()

    if form.validate_on_submit():
        session['remember_me'] = form.remember_me.data
        return oid.try_login(form.openid.data,ask_for=['nickname','email'])
    return render_template('login.html',
                           title = 'Sign In',
                           form = form,
                           providers = app.config['OPENID_PROVIDERS']
                           )



#user_loader 回调
@lm.user_loader
def load_user(id):
    return User.query.get(int(id))


@oid.after_login
def after_login(resp):
    if resp.email is None or resp.email == "":
        flash('Invalid login. Please try again.')
        return redirect(url_for('login'))
    user = User.query.filter_by(email=resp.email).first()
    if user is None:
        nickname = resp.nickname
        if nickname is None or nickname == "":
            nickname = resp.email.split('@')[0]
        user = User(nickname=nickname, email=resp.email)
        db.session.add(user)
        db.session.commit()
    remember_me = False
    if 'remember_me' in session:
        remember_me = session['remember_me']
        session.pop('remember_me', None)
    login_user(user, remember = remember_me)
    return redirect(request.args.get('next') or url_for('index'))


@app.before_request
def before_request():
    #用 Flask 的 before_request 装饰器
    g.user = current_user
#用户的登录页面
@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('index'))

#用户的信息页
@app.route('/user/<nickname>')
@login_required
def user(nickname):
    user = User.query.filter_by(nickname = nickname).first()
    if user == None:
        flash('User'+ nickname + 'not found')
        return redirect(url_for('index'))
    posts =  [
        { 'author': user, 'body': 'Test post #1' },
        { 'author': user, 'body': 'Test post #2' }
    ]

    return render_template('user.html',
                           user = user,
                           posts = posts)


